
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:xim/common/style/colors.dart';
import 'package:xim/common/util/system.dart';
import 'package:xim/common/util/toast.dart';
import 'package:xim/common/util/utility.dart';
import 'package:xim/config/route_config.dart';
import 'package:xim/widget/common/state.dart';
import 'package:flutter/foundation.dart';

/// webView 页面
class WebViewPage extends StatefulWidget {

  final String content;

  const WebViewPage({Key? key, required this.content}) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> with AppBarMixin, BrightnessModeState{

  ModelColor textColor = ModelColor(lightColor: const Color((0xff161616)), darkColor: const Color(0xffcecece));
  ModelColor bgColor = ModelColor(darkColor: Colors.black, lightColor: Colors.white);
  String _webTitle = "";
  final GlobalKey webViewKey = GlobalKey();

  @override
  double get elevation =>0.1;

  @override
  String get appBarTitle => _webTitle.ellipsis(8);

  @override
  Color get appBarBgColor => bgColor.color;

  @override
  List<ModelColor> get brightnessColors => [textColor,bgColor];

  @override
  TextStyle get appBarTitleStyle => TextStyle(color: textColor.color, fontSize: 14);

  @override
  IconThemeData get iconTheme => IconThemeData(color: textColor.color, );

  @override
  List<Widget> get appBarActions => [
    IconButton(onPressed: (){
      ToastUtil.bottomSelectedSheet(
          children: [
            GestureDetector(
              onTap: (){
                Utility.copyToClipboard(widget.content);
                Routers.back();
              },
              behavior:HitTestBehavior.opaque,
              child: const Text("复制")
            ),
            // const Text("分享"),
          ]
      );
    }, icon: const Icon(Icons.more_horiz))
  ];

  @override
  Widget? get leading => GestureDetector(
    onTap: ()=> Routers.back(),
    child: const Icon(Icons.close),
  );

  InAppWebViewController? webViewController;
  PullToRefreshController? pullToRefreshController;
  PullToRefreshSettings pullToRefreshSettings = PullToRefreshSettings(
    color: Colors.blue,
  );

  double progress = 0;

  InAppWebViewSettings settings = InAppWebViewSettings(
      algorithmicDarkeningAllowed:true,
      javaScriptEnabled: true,
      allowBackgroundAudioPlaying:false,
      isInspectable: kDebugMode,
  );

  @override
  void initState() {
    super.initState();
    pullToRefreshController = kIsWeb ? null : PullToRefreshController(
      settings: pullToRefreshSettings,
      onRefresh: () async {
        if (defaultTargetPlatform == TargetPlatform.android) {
          webViewController?.reload();
        } else if (defaultTargetPlatform == TargetPlatform.iOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl())
          );
        }
      },
    );
    pullToRefreshController?.setEnabled(true);
  }

  @override
  Widget build(BuildContext context) {
    initModelColor(context);
    Uri? uri;
    if (widget.content.toLowerCase().startsWith("http")) {
      uri = Uri.parse(widget.content);
    } else {
      uri = null;
    }
    return Scaffold(
      appBar: appBar,
      body: PopScope(
        canPop: false,
        onPopInvoked: (e) async {
          if(e){
            return;
          }
          var isFinish = await webViewController?.canGoBack();
          if(isFinish!=null && isFinish){
            webViewController?.goBack();
            return;
          }
          Routers.back();
        },
        child: uri==null
            ? Text(widget.content, style: const TextStyle(color: Colors.black),)
            : Stack(
          children: [
            InAppWebView(
              key: webViewKey,
              initialUrlRequest: URLRequest(url: WebUri(uri.toString())),
              pullToRefreshController: pullToRefreshController,
              initialSettings: settings,
              onWebViewCreated: (InAppWebViewController controller) {
                webViewController = controller;
              },
              onTitleChanged: (controller, title) {
                if(title!=null && title!=""){
                  setState(() {
                    _webTitle = title;
                  });
                }
              },
              onUpdateVisitedHistory: (InAppWebViewController controller, WebUri? url, bool? isReload){

              },
              onLoadStop:(controller, url)=>pullToRefreshController?.endRefreshing(),
              onReceivedError: (controller, request, error) {
                pullToRefreshController?.endRefreshing();
              },
              onProgressChanged: (controller, progress) {
                if (progress == 100) {
                  pullToRefreshController?.endRefreshing();
                }
                setState(() {
                  this.progress = progress / 100;
                });
              },
            ),
            progress < 1.0
                ? LinearProgressIndicator(value: progress, minHeight: 2,)
                : Container(),
          ],
        ),
      ),
    );
  }
}
